package com.ebeitech.camera;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Camera.ShutterCallback;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.OrientationEventListener;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.ebeitech.doorapp.util.PublicUtil;
import com.ebeitech.doorapp.view.OnInitializeListener;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.doorapp.R;
import com.ebeitech.library.util.SPManager;
import com.ebeitech.library.util.TimeUtil;
import com.ebeitech.library.util.ViewUtil;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class VideoFragment extends Fragment implements SurfaceHolder.Callback {

	private static final int ROTATION_ORIGI = 0;
	private static final String TAG = "VideoActviity";
	private Context mContext;
	private ImageView start = null;
	//private View stop = null;
	private View exit = null;
	//private View back = null;
	private View use = null;
	//private TextView tvStart = null;
	//private TextView tvExit = null;
	private MediaRecorder mediarecorder = null;
	private SurfaceView surfaceview = null;
	private Camera mCamera = null;
	private String path = "";
	private Chronometer timer = null;
	private boolean isVideo = true;
	private ArrayList<String> photos = null;
	private static final int REQUEST_PREVIEW = 0X911;
	private static final int REQUEST_AUTO_FOCUS = 0X912;

	private static final int AUTO_FOCUS_DELAY = 36 * 100;

	public static final String BITMAP_PATH_EXTRA = "bitmap path extra";
	public static final String BITMAP_EXTRA = "bitmap extra";
	private int IMAGE_WIDTH = 720;
	private int IMAGE_HEIGHT = 480;
	private static final int IMAGE_QUALITY = 80;
	private View recodertext = null;
	private View settingLayout = null;
	private String[] settingLevels = null;
	private PopupWindow popupWindow = null;
	private final String PICTURE_WIDTH = "PICTURE_WIDTH";
	private final String PICTURE_HEIGHTH = "PICTURE_HEIGHTH";
	private final String FLASH_LIGHT_SETTING = "FLASH_LIGHT_SETTING";
	private boolean shouldTakePhoto = false;
	private Timer t = null;
	private boolean isFocus = false;
	//private TextView tvFlashLightSetting = null;
	private ImageView ivFlashLightSetting = null;

	boolean shouldInit = true;
	boolean isVideoRecording = false;
	private int mLastRotation;
	private boolean isGranted = true;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.what;
			if (REQUEST_PREVIEW == what) {
				Intent intent = new Intent(mContext,
						QPIPicturePreviewActivity.class);
				intent.putExtras(msg.getData());
				intent.putExtra(SPConstants.PHOTOS_KEY, photos);
				startActivityForResult(intent, REQUEST_PREVIEW);
			} else if (REQUEST_AUTO_FOCUS == what) {
				if (mCamera != null) {
					try {
						if (!isFocus) {
							isFocus = true;
							mCamera.autoFocus(autoFocusCb);
							TimerTask task = new MyTimerTask();
							t.schedule(task, AUTO_FOCUS_DELAY);
						}
					} catch (Exception ex) {
						ex.printStackTrace();
						isFocus = false;
						if (shouldTakePhoto) {
							takePhoto();
							shouldTakePhoto = false;
						}
					}
				}
			}
		}
	};

	private SurfaceHolder surfaceHolder = null;
	
	private boolean mCurrentOrient = false;
	private boolean mScreenProtrait = true;
	private OrientationEventListener mOrientationEventListener;
	private OnInitializeListener mInitializeListener;
	
	public void setOnInitializeListener(OnInitializeListener l) {
		mInitializeListener = l;
	}

	public void setIsVideo(boolean isVideo) {
		this.isVideo = isVideo;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mContext = getActivity();
		View view = inflater.inflate(R.layout.ebei_activity_media_video, null);
		init(view);
		setupFlashSettingLayout();
		mOrientationEventListener = new MyOrientationEventListener(mContext);
		mOrientationEventListener.enable();
		
		if (!PublicUtil.checkSelfPermission(mContext, Manifest.permission.CAMERA)) {
			isGranted = false;
			PublicUtil.requestPermissions(this, Manifest.permission.CAMERA, 1);
		}
		return view;
	}

	private void setupFlashSettingLayout() {
		String flashLightSetting = SPManager.getInstance(mContext).get(FLASH_LIGHT_SETTING, Parameters.FLASH_MODE_OFF);
		Resources res = getResources();
		int textColor = res.getColor(R.color.ebei_golden);
		if (Parameters.FLASH_MODE_OFF.equals(flashLightSetting)) {
			//tvFlashLightSetting.setText(R.string.open);
			//ivFlashLightSetting.setImageResource(R.drawable.flash_light_on);
			ivFlashLightSetting.setImageResource(R.drawable.ebei_camera_flash_off);
			//tvFlashLightSetting.setTextColor(textColor);
		} else if (Parameters.FLASH_MODE_TORCH.equals(flashLightSetting)) {
			textColor = res.getColor(R.color.ebei_video_text_color);
			//tvFlashLightSetting.setText(R.string.closed);
			//ivFlashLightSetting.setImageResource(R.drawable.flash_light_off);
			ivFlashLightSetting.setImageResource(R.drawable.ebei_camera_flash_on);
			//tvFlashLightSetting.setTextColor(textColor);
		}
	}
	
	//@Override
	public void onRequestPermissionsResult(int requestCode,
			String[] permissions, int[] grantResults) {
		// TODO Auto-generated method stub
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		isGranted = true;
		for (int i = 0; i < grantResults.length; i++) {
			if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
				isGranted = false;
			}
		}
		if (isGranted) {
			if (mCamera == null) {
				onResume();
			}
		} else {
			((Activity) mContext).finish();
		}
	}

	public void onResume() {
		super.onResume();
		
		if (!isGranted) {
			return;
		}
		
		if (shouldInit) {
			recycle();
			if (mCamera == null) {
				initCamera();
				if (mInitializeListener != null) {
					mInitializeListener.onFinished();
				}
			}
			TimerTask task = new MyTimerTask();
			if (t == null) {
				t = new Timer();
			}
			t.schedule(task, AUTO_FOCUS_DELAY);
		}
	}
	private void recycle() {
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
		}
	}
	private class MyTimerTask extends TimerTask {

		public void run() {
			Message message = handler.obtainMessage(REQUEST_AUTO_FOCUS);
			handler.sendMessage(message);
		}

	};

	@SuppressLint("NewApi") @SuppressWarnings("deprecation")
	private void init(View view) {
		SPManager sp = SPManager.getInstance(mContext);
		IMAGE_WIDTH = sp.get(PICTURE_WIDTH, 720);
		IMAGE_HEIGHT = sp.get(PICTURE_HEIGHTH, 480);
		float mCurrentRotation = -ROTATION_ORIGI;
		
		Intent intent = getActivity().getIntent();
		/*if (intent != null && intent.hasExtra(SPConstants.IS_VIDEO)) {
			isVideo = intent.getBooleanExtra(SPConstants.IS_VIDEO, true);
		}*/
		
		start = (ImageView) view.findViewById(R.id.start);
		start.setImageResource(R.drawable.ebei_vedio_start_selector);
		//stop = (View) this.findViewById(R.id.stop);
		
		exit = (View) view.findViewById(R.id.exit);
		use = view.findViewById(R.id.use);
		use.setVisibility(View.GONE);
		view.findViewById(R.id.use_count).setVisibility(View.GONE);
		view.findViewById(R.id.view_use).setVisibility(View.VISIBLE);
		//back = findViewById(R.id.back);
		timer = (Chronometer) view.findViewById(R.id.recodertext);
		start.setOnClickListener(recordVideoListener);
		//stop.setOnClickListener(stopRecordListener);
		exit.setOnClickListener(exitRecordListener);
		//back.setOnClickListener(backListener);
		use.setOnClickListener(useListener);
		surfaceview = (SurfaceView) view.findViewById(R.id.surfaceview);
		surfaceHolder = surfaceview.getHolder();// holder
		surfaceHolder.addCallback(this); // holder
		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		surfaceHolder.setKeepScreenOn(true);
		recodertext = view.findViewById(R.id.recodertext);
		settingLayout = view.findViewById(R.id.ivSetting);
		settingLayout.setVisibility(View.GONE);
		if (isVideo) {
			surfaceHolder.setFixedSize(320, 240);
			//settingLayout.setVisibility(View.GONE);
			
			int fixWidth = 240;
			int fixHeight = 320;
			int screenWidth = ViewUtil.getScreenSize(getActivity()).widthPixels;
			int screenHeight = ViewUtil.getScreenSize(getActivity()).heightPixels;
			RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) surfaceview.getLayoutParams();
			if(screenWidth * fixHeight > screenHeight * fixWidth) {
				lp.width = fixWidth * screenHeight / fixHeight;
				lp.height = screenHeight;
			} else {
				lp.width = screenWidth;
				lp.height = fixHeight * screenWidth / fixWidth;
			}
			surfaceview.setLayoutParams(lp);
		} else {
			surfaceHolder.setFixedSize(IMAGE_WIDTH, IMAGE_HEIGHT);
			recodertext.setVisibility(View.GONE);
			//settingLayout.setVisibility(View.VISIBLE);
		}
		//tvStart = (TextView) findViewById(R.id.tvStart);
		//tvExit = (TextView) findViewById(R.id.tvExit);
		if (!isVideo) {
			//stop.setVisibility(View.GONE);
			//tvStart.setText(R.string.take_photo);
			//tvExit.setText(R.string.go_out);

			// DrawCaptureRect mDraw = new DrawCaptureRect(this, 190, 10, 100,
			// 100, Color.RED);
			// addContentView(mDraw, new LayoutParams(LayoutParams.WRAP_CONTENT,
			// LayoutParams.WRAP_CONTENT));
			// this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
		}

		settingLevels = getResources().getStringArray(
				R.array.ebei_camera_setting_levels);
		//tvFlashLightSetting = (TextView) findViewById(R.id.tvFlashSetting);
		ivFlashLightSetting = (ImageView) view.findViewById(R.id.ivFlashSetting);
		ivFlashLightSetting.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onFlashSettingLayoutClicked(arg0);
			}
		});

		PublicUtil.setRotation(start, mCurrentRotation);
		PublicUtil.setRotation(ivFlashLightSetting, mCurrentRotation);
		PublicUtil.setRotation(use, mCurrentRotation);
	}

	private OnClickListener recordVideoListener = new OnClickListener() {

		public void onClick(View v) {
			if (isVideo) {
				if (!isVideoRecording) {
					isVideoRecording = true;
					recodertext.setVisibility(View.VISIBLE);
					//start.setVisibility(View.GONE);
					//exit.setVisibility(View.GONE);
					//stop.setVisibility(View.VISIBLE);
					//back.setVisibility(View.GONE);
					use.setVisibility(View.GONE);
					startRecorder(v);
				} else {
					start.setEnabled(false);
					stopRecord();
					
					isVideoRecording = false;
					//exit.setVisibility(View.VISIBLE);
					use.setVisibility(View.VISIBLE);
				}
			} else {
				startRecorder(v);
			}
		}
	};

	private OnClickListener stopRecordListener = new OnClickListener() {

		public void onClick(View v) {
			stopRecord();

			start.setVisibility(View.GONE);
			//exit.setVisibility(View.GONE);
			//stop.setVisibility(View.GONE);
			//back.setVisibility(View.VISIBLE);
			use.setVisibility(View.VISIBLE);
		}
	};

	public void onFlashSettingLayoutClicked(View v) {

		String flashLightSetting = SPManager.getInstance(mContext).get(FLASH_LIGHT_SETTING, Parameters.FLASH_MODE_OFF);
		String mode = flashLightSetting;
		if (Parameters.FLASH_MODE_OFF.equals(flashLightSetting)) {
			mode = Parameters.FLASH_MODE_TORCH;
		} else if (Parameters.FLASH_MODE_TORCH.equals(flashLightSetting)) {
			mode = Parameters.FLASH_MODE_OFF;
		}
		if (mCamera != null) {
			Parameters parameters = mCamera.getParameters();
			try {
				parameters.setFlashMode(mode);
				mCamera.setParameters(parameters);
				SPManager.getInstance(mContext).put(FLASH_LIGHT_SETTING, mode);
				setupFlashSettingLayout();
			} catch (Exception e) {
				e.printStackTrace();
				Toast.makeText(mContext, R.string.ebei_flashlight_unsurpported,
						Toast.LENGTH_SHORT).show();
				;
			}
		}
	}

	private OnClickListener exitRecordListener = new OnClickListener() {

		public void onClick(View v) {
			if (isVideoRecording) {
				start.setEnabled(true);
				stopRecord();
				File file = new File(path);
				if(file.exists()){
					file.delete();
				}
				initCamera();
				
				isVideoRecording = false;
				recodertext.setVisibility(View.GONE);
				use.setVisibility(View.GONE);
			} else {
				//start.setVisibility(View.VISIBLE);
				exit.setVisibility(View.VISIBLE);
				//stop.setVisibility(View.GONE);
				//back.setVisibility(View.GONE);
				use.setVisibility(View.GONE);
				if (photos != null && photos.size() > 0) {
					Intent data = new Intent();
					data.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_VIDEO);
					data.putExtra(SPConstants.PHOTOS_KEY, photos);
					((Activity) mContext).setResult(Activity.RESULT_OK, data);
				}
				((Activity) mContext).finish();
			}
		}
	};

	private OnClickListener backListener = new OnClickListener() {

		public void onClick(View v) {

			stopRecord();
			File file = new File(path);
			file.delete();
			initCamera();
			start.setVisibility(View.VISIBLE);
			exit.setVisibility(View.VISIBLE);
			//stop.setVisibility(View.GONE);
			//back.setVisibility(View.GONE);
			use.setVisibility(View.GONE);
		}
	};

	private void initCamera() {
		if (mCamera == null) {

			try {
				mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
				VideoFragment.this.setCamera(mCamera);
				mCamera.setDisplayOrientation(getCameraDisplayOrientation(getActivity(), CameraInfo.CAMERA_FACING_BACK, mCamera));
				mCamera.setPreviewDisplay(surfaceHolder);
				mCamera.startPreview();
			} catch (IOException e) {
				recycle();
				e.printStackTrace();
			}
		}
	}
	
	private int getCameraDisplayOrientation(Activity activity, int cameraId, Camera camera) {
		CameraInfo info = new CameraInfo();
		Camera.getCameraInfo(cameraId, info);
		int rotation = activity.getWindowManager().getDefaultDisplay().getRotation();
		int degrees = 0;
		switch (rotation) {
		case Surface.ROTATION_0:
			degrees = 0;
			break;
		case Surface.ROTATION_90:
			degrees = 90;
			break;
		case Surface.ROTATION_180:
			degrees = 180;
			break;
		case Surface.ROTATION_270:
			degrees = 270;
			break;
		default:
			break;
		}
		int result = 0;
		if(info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
			result = (info.orientation + degrees) % 360;
			result = (360 - result) % 360;
		} else {
			result = (info.orientation - degrees + 360) % 360;
		}
		return result;
	}

	private AutoFocusCallback autoFocusCb = new AutoFocusCallback() {

		@Override
		public void onAutoFocus(boolean success, Camera camera) {
			// TODO Auto-generated method stub
			if(mCamera!=null)
			mCamera.setOneShotPreviewCallback(null);
			if (success) {
				// Toast.makeText(VideoActviity.this,
				// R.string.auto_focus_success,
				// Toast.LENGTH_SHORT).show();
				// ;
			}
			if (shouldTakePhoto) {
				takePhoto();
				shouldTakePhoto = false;
			}
			isFocus = false;
		}
	};

	private OnClickListener useListener = new OnClickListener() {

		public void onClick(View v) {
			Intent i = new Intent();
			Bundle b = new Bundle();
			b.putString("mediapath", path);
			i.putExtras(b);
			i.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_VIDEO);
			((Activity) mContext).setResult(Activity.RESULT_OK, i);

			//start.setVisibility(View.VISIBLE);
			exit.setVisibility(View.VISIBLE);
			//stop.setVisibility(View.GONE);
			//back.setVisibility(View.GONE);
			use.setVisibility(View.GONE);
			((Activity) mContext).finish();
		}
	};

	private void startRecorder(View v) {
		if (isVideo) {
			timer.setBase(SystemClock.elapsedRealtime());
			timer.start();
			try {
				mediarecorder = new MediaRecorder();
				prepareVideoRecorder();
				mediarecorder.start();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			if (PublicUtil.shouldCommit(v)) {
				start.setClickable(false);
				start.setOnClickListener(null);
				shouldTakePhoto = true;
				Message message = handler.obtainMessage(REQUEST_AUTO_FOCUS);
				handler.sendMessage(message);
			}
		}
	}

	private void takePhoto() {
		if (mCamera != null) {
			start.setEnabled(false);
			start.setClickable(false);
			mCamera.takePicture(shuttercallback, rawcallback, picturecallback);
		}
	}

	private ShutterCallback shuttercallback = new ShutterCallback() {

		@Override
		public void onShutter() {
			// TODO Auto-generated method stub

		}
	};
	private PictureCallback rawcallback = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub

		}
	};
	private PictureCallback picturecallback = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] data, Camera camera) {
			// TODO Auto-generated method stub
			Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
			Bitmap bitmap = zoomImg(bm, IMAGE_WIDTH, IMAGE_HEIGHT);
			if (bitmap != bm) {
				bm.recycle();
			}

			bm = null;
			bm = bitmap;

			int width = bm.getWidth();
			int height = bm.getHeight();
			Bitmap icon = Bitmap.createBitmap(width, height,
					Bitmap.Config.ARGB_8888); // create an empty new bitmap
			Canvas canvas = new Canvas(icon);// create a canvas

			Paint photoPaint = new Paint(); // create paint
			photoPaint.setDither(true);
			photoPaint.setFilterBitmap(true);

			Rect src = new Rect(0, 0, width, height);
			Rect dst = new Rect(0, 0, width, height);
			canvas.drawBitmap(bm, src, dst, photoPaint);

			canvas.save(Canvas.ALL_SAVE_FLAG);
			canvas.restore();

			if (icon != bm) {
				bm.recycle();
				bm = null;
			}

			String picturePath = PublicUtil.getAppFile(mContext) + "/"
					+ TimeUtil.getCurrentTime("yyyyMMdd_HHmmss") + ".jpg";
			File picFile = new File(picturePath);
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(picFile));
				icon.compress(Bitmap.CompressFormat.JPEG, IMAGE_QUALITY, bos);
				stopRecord();
				initCamera();
				if (picFile.exists()) {
					Message msg = handler.obtainMessage(REQUEST_PREVIEW);
					Bundle b = new Bundle();
					b.putString(BITMAP_PATH_EXTRA, picturePath);
					// b.putParcelable(BITMAP_EXTRA, icon);
					msg.setData(b);
					handler.sendMessage(msg);
				} else {
					Toast.makeText(mContext, R.string.ebei_camera_error_happen,
							Toast.LENGTH_LONG).show();
				}

			} catch (Exception e) {
				e.printStackTrace();
			}

			start.setEnabled(true);
			start.setClickable(true);
		}
	};

	private boolean prepareVideoRecorder() {
		try {
			mCamera.unlock();
		} catch (Exception e) {
		}
		String time = TimeUtil.getCurrentTime("yyyyMMdd_HHmmss");
		path = PublicUtil.getAppFile(mContext) + "/" + time + ".3gp";
		mediarecorder.setCamera(mCamera);
		mediarecorder.setOrientationHint(90);
		mediarecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
		mediarecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
		mediarecorder.setProfile(CamcorderProfile
				.get(CamcorderProfile.QUALITY_LOW));
		mediarecorder.setVideoSize(320, 240);
		mediarecorder.setPreviewDisplay(surfaceHolder.getSurface());
		mediarecorder.setOutputFile(path);
		try {
			mediarecorder.prepare();
		} catch (Exception e) {
			return false;
		}
		return true;
	}

	private void stopRecord() {
		if (mediarecorder != null) {
			try {
				//延时1s 防止MediaRecorder.start()与stop()间隔过短
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (mediarecorder != null) {
				mediarecorder.setOnErrorListener(null);
				try{
					mediarecorder.stop();
				}catch(Exception e){
					
				}
				mediarecorder.reset();
				mediarecorder.release();
				mediarecorder = null;
			}
		}

		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;

		}
		if (timer != null) {
			timer.stop();
			//timer.setBase(SystemClock.elapsedRealtime());
		}
	}

	public void setCamera(Camera camera) {
		mCamera = camera;
		if (mCamera != null && surfaceview != null) {
			surfaceview.requestLayout();
		}
	}

	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		if(mCamera != null){
			mCamera.startPreview();
		}
		Log.i("VideoFragment", "surfaceChanged");
	}

	public void surfaceCreated(SurfaceHolder holder) {
		try {
			if (mCamera != null) {
				mCamera.setPreviewDisplay(holder);
				mCamera.startPreview();
				try {
					mCamera.autoFocus(autoFocusCb);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (IOException e) {
			mCamera.release();
			mCamera = null;

		}
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		if (mediarecorder != null) {
			try{
				mediarecorder.stop();
			}catch(Exception e){
				
			}
			mediarecorder.release();
			mediarecorder = null;
		}
		if (mCamera != null) {
			mCamera.stopPreview();
			mCamera.release();
			mCamera = null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		boolean shouldFinish = true;

		start.setClickable(true);
		start.setOnClickListener(recordVideoListener);
		if (REQUEST_PREVIEW == requestCode) {
			if (QPIPicturePreviewActivity.RESULT_NEXT == resultCode) {
				shouldFinish = false;
			} else if (QPIPicturePreviewActivity.RESULT_RECAPURE == resultCode) {
				return;
			}

			photos = (ArrayList<String>) data
					.getSerializableExtra(SPConstants.PHOTOS_KEY);

			if (shouldFinish) {
				shouldInit = false;
				if (photos != null && photos.size() > 0) {
					Intent intent = new Intent();
					intent.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_VIDEO);
					intent.putExtra(SPConstants.PHOTOS_KEY, photos);
					((Activity) mContext).setResult(Activity.RESULT_OK, intent);
				}
				stopRecord();
				((Activity) mContext).finish();
			}
		}
	}

	public static Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
		// get the width and height of the original picture
		int width = bm.getWidth();
		int height = bm.getHeight();
		// find the scale rate
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		// set the scale matrix parameters
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		// create new bitmap
		Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix,
				true);
		return newbm;
	}

	class DrawCaptureRect extends View {
		private int mcolorfill;
		private int mleft, mtop, mwidth, mheight;

		public DrawCaptureRect(Context context, int left, int top, int width,
				int height, int colorfill) {
			super(context);
			// TODO Auto-generated constructor stub
			this.mcolorfill = colorfill;
			this.mleft = left;
			this.mtop = top;
			this.mwidth = width;
			this.mheight = height;
		}

		@Override
		protected void onDraw(Canvas canvas) {
			// TODO Auto-generated method stub
			Paint mpaint = new Paint();
			mpaint.setColor(mcolorfill);
			mpaint.setStyle(Paint.Style.FILL);
			mpaint.setStrokeWidth(1.0f);
			canvas.drawLine(mleft, mtop, mleft + mwidth, mtop, mpaint);
			canvas.drawLine(mleft + mwidth, mtop, mleft + mwidth, mtop
					+ mheight, mpaint);
			canvas.drawLine(mleft, mtop, mleft, mtop + mheight, mpaint);
			canvas.drawLine(mleft, mtop + mheight, mleft + mwidth, mtop
					+ mheight, mpaint);
			super.onDraw(canvas);
		}

	}
	
	@SuppressLint("NewApi")
	class MyOrientationEventListener extends OrientationEventListener {

		public MyOrientationEventListener(Context context) {
			super(context);
			// TODO Auto-generated constructor stub
		}

		@Override
		public void onOrientationChanged(int rotation) {
			// TODO Auto-generated method stub
			System.out.println("rotation =====>" + rotation);
			if (((rotation >= 0) && (rotation <= 45)) || (rotation >= 315)||((rotation>=135)&&(rotation<=225))) {//portrait
				// protrait
				mCurrentOrient = true;
				if (mCurrentOrient != mScreenProtrait) {
					mScreenProtrait = mCurrentOrient;
					Log.i(TAG ,"竖屏");
					int widgetRotation = -ROTATION_ORIGI;
					PublicUtil.setRotation(start, widgetRotation);
					PublicUtil.setRotation(ivFlashLightSetting, widgetRotation);
					PublicUtil.setRotation(use, widgetRotation);
					mLastRotation = rotation;
				}
			} else if (((rotation > 45) && (rotation < 135))
					|| ((rotation > 225) && (rotation < 315))) {
				// landscape
				mCurrentOrient = false;
				if (Math.abs(mLastRotation - rotation) > 90 || mCurrentOrient != mScreenProtrait) {
					mScreenProtrait = mCurrentOrient;
					Log.i(TAG ,"横屏");
					int widgetRotation = 0;
					if(rotation < 135) {
						widgetRotation = 270 - ROTATION_ORIGI;
					} else {
						widgetRotation = 90 - ROTATION_ORIGI;
					}
					PublicUtil.setRotation(start, widgetRotation);
					PublicUtil.setRotation(ivFlashLightSetting, widgetRotation);
					PublicUtil.setRotation(use, widgetRotation);
					mLastRotation = rotation;
				}
			}
		}
		
	};

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onStop()
	 */
	@Override
	public void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		if (t != null) {
			t.cancel();
			t = null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onBackPressed()
	 */
	private void onBackPressed() {
		// TODO Auto-generated method stub
		((Activity) mContext).onBackPressed();
		if (photos != null && photos.size() > 0) {
			Intent data = new Intent();
			data.putExtra(SPConstants.FILE_TYPE, SPConstants.REQUEST_VIDEO);
			data.putExtra(SPConstants.PHOTOS_KEY, photos);
			((Activity) mContext).setResult(Activity.RESULT_OK, data);
		}
		((Activity) mContext).finish();
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mOrientationEventListener != null) {
			mOrientationEventListener.disable();
		}
	}
}
